<template>
<el-form-item :prop="prop" :label="label" :rules="rulesList">
  <el-date-picker v-model="text" :type="type" :start-placeholder="placeholder||placeholderText" :end-placeholder="placeholder||placeholderText" :value-format="valueFormat" v-bind="$attrs" v-on="$listeners" :picker-options="limit&&expireTimeOption" />
</el-form-item>
</template>

<script>
import fecha from '@/utils/external/date'
import { mixin } from './mixin'

export default {
  name: 'DateRange',
  mixins: [mixin],
  props: {
    limit:{
      type:Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'daterange'
    },
    valueFormat: {
      type: String,
      default: 'yyyy-MM-dd'
    },
    startTime: null,
    endTime: null
  },
  data() {
    return {
      placeholderText: '选择日期',
      expireTimeOption: {
        disabledDate(date) {
          // 当天可选：date.getTime() < Date.now() - 24 * 60 * 60 * 1000
          return date.getTime() < Date.now()
        }
      }
    }
  },
  computed: {
    text: {
      get() {
        const isTimestamp = this.valueFormat === 'timestamp'
        if (this.startTime && this.endTime) {
          const startTime = isTimestamp ? this.startTime : fecha.format(new Date(this.startTime), this.valueFormat)
          let endTime = null
          endTime = new Date(this.endTime)
          if (this.valueFormat === 'yyyy-MM-dd') {
            endTime = endTime.setDate(endTime.getDate() - 1)
          }
          endTime = isTimestamp ? endTime.getTime() : fecha.format(new Date(endTime), this.valueFormat)
          return [startTime, endTime]
        }
        return null
      },
      set(val) {
        const isTimestamp = this.valueFormat === 'timestamp'
        let startTime = null
        let endTime = null
        if (val) {
          startTime = val[0]
          endTime = val[1]
          if (this.valueFormat && !isTimestamp) {
            endTime = new Date(endTime)
            if (this.valueFormat === 'yyyy-MM-dd') {
              endTime = endTime.setDate(endTime.getDate() + 1)
            }
            endTime = fecha.format(new Date(endTime), this.valueFormat)
          }
        }
        this.$emit('update:startTime', startTime)
        this.$emit('update:endTime', endTime)
      },
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-date-editor--daterange.el-input,
.el-date-editor--daterange.el-input__inner,
.el-date-editor--timerange.el-input,
.el-date-editor--timerange.el-input__inner {
  min-width: 250px;
  max-width: 300px;
}
</style>
